<template>
  <div class="activity-detail">
    <!-- 活动头部信息 -->
    <div class="activity-header">
      <div class="activity-cover">
        <el-image :src="activity.coverImg" fit="cover"/>
      </div>
      <div class="activity-info">
        <h1 class="activity-title">{{ activity.title }}</h1>
        <div class="activity-meta">
          <div class="meta-item">
            <el-icon>
              <Location/>
            </el-icon>
            <span>{{ activity.location }}</span>
          </div>
          <div class="meta-item">
            <el-icon>
              <User/>
            </el-icon>
            <span>{{ activity.team }}</span>
          </div>
          <div class="meta-item">
            <el-icon>
              <Timer/>
            </el-icon>
            <span>{{ formatDateTime(activity.startTime) }} - {{ formatDateTime(activity.endTime) }}</span>
          </div>
        </div>
        <div class="activity-status">
          <el-tag :type="getStatusType(activity.status)">
            {{ getStatusText(activity.status) }}
          </el-tag>
          <span class="recruit-info">
            已报名 {{ activity.recruitNumber }}/{{ activity.registeredNumber }} 人
          </span>
        </div>
        <div class="activity-actions">
          <el-button
              type="primary"
              @click="handleRegister"
          >
            {{ getRegisterButtonText(activity) }}
          </el-button>
          <el-button
              :type="activity.isCollected ? 'success' : 'default'"
              @click="handleCollect"
          >
            <el-icon>
              <Star/>

            </el-icon>
            {{ activity.isCollected ? '已收藏' : '收藏' }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 活动详情内容 -->
    <div class="activity-content">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="活动详情" name="detail">
          <div class="detail-section">
            <h2>活动介绍</h2>
            <p>{{ activity.description }}</p>
          </div>
          <div class="detail-section">
            <h2>报名须知</h2>
            <p>报名时间：{{ formatDateTime(activity.registerStartTime) }} - {{
                formatDateTime(activity.registerEndTime)
              }}</p>
            <p>活动地点：{{ activity.location }}</p>
            <p>招募人数：{{ activity.registeredNumber }}人</p>
          </div>
        </el-tab-pane>

        <el-tab-pane label="评论区" name="comments">
          <!-- 评论输入框 -->
          <div class="comment-input">
            <el-input
                v-model="commentContent"
                type="textarea"
                :rows="3"
                :placeholder="replyTo ? `回复 ${replyTo.username}：` : '写下你的评论...'"
            />
            <div class="comment-actions">
              <el-button v-if="replyTo" @click="cancelReply">取消回复</el-button>
              <el-button type="primary" @click="submitComment">发表评论</el-button>
            </div>
          </div>

          <!-- 评论列表 -->
          <div class="comment-list">
            <CommentItem
                v-for="comment in comments"
                :key="comment.id"
                :comment="comment"
                @like="handleLike"
                @reply="handleReply"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, defineComponent} from 'vue'
import {useRoute} from 'vue-router'
import {ElMessage} from 'element-plus'
import {Location, User, Timer, Star, Pointer} from '@element-plus/icons-vue'
import {getActivityDetail, registerActivity} from '@/api/activity'
import {createComment, getComments, likeComment} from '@/api/comment'
import {addCollection, cancelCollection, checkUserCollected} from '@/api/collection'
import {useUserStore} from '@/stores/user'
import CommentItem from '@/components/CommentItem.vue'

const route = useRoute()
const userStore = useUserStore()
const activity = ref({})
const activeTab = ref('detail')
const commentContent = ref('')
const comments = ref([])
const loading = ref(false)
const replyTo = ref(null)

// 获取活动详情
const fetchActivityDetail = async () => {
  try {
    loading.value = true
    const {data} = await getActivityDetail(route.params.id)
    activity.value = data

    // 检查用户是否已收藏此活动
    if (userStore.isLoggedIn) {
      try {
        const {data: isCollected} = await checkUserCollected(route.params.id)
        activity.value.isCollected = isCollected
      } catch (err) {
        console.error('检查收藏状态失败:', err)
      }
    }
  } catch (error) {
    ElMessage.error('获取活动详情失败')
  } finally {
    loading.value = false
  }
}

// 获取评论列表
const getCommentList = async () => {
  try {
    const {data} = await getComments(route.params.id)
    comments.value = data
  } catch (error) {
    ElMessage.error('获取评论列表失败')
  }
}

// 提交评论
const submitComment = async () => {
  if (!commentContent.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  try {
    await createComment({
      activityId: route.params.id,
      parentId: replyTo.value?.id,
      content: commentContent.value
    })
    ElMessage.success('评论发表成功')
    commentContent.value = ''
    replyTo.value = null
    getCommentList() // 刷新评论列表
  } catch (error) {
    ElMessage.error('评论发表失败')
  }
}

// 收藏活动
const handleCollect = async () => {
  try {
    if (activity.value.isCollected) {
      await cancelCollection(route.params.id)
    } else {
      await addCollection(route.params.id)
    }
    activity.value.isCollected = !activity.value.isCollected
    ElMessage.success(activity.value.isCollected ? '收藏成功' : '已取消收藏')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 报名活动
const handleRegister = async () => {
  try {
    await registerActivity(route.params.id)
    ElMessage.success('报名成功')
    fetchActivityDetail() // 刷新活动详情
  } catch (error) {
    ElMessage.error(error.message || '报名失败')
  }
}

// 点赞评论
const handleLike = async (comment) => {
  try {
    await likeComment(comment.id)
    comment.likes++
    ElMessage.success('点赞成功')
  } catch (error) {
    ElMessage.error('点赞失败')
  }
}

// 回复评论
const handleReply = (comment) => {
  replyTo.value = comment
  commentContent.value = `@${comment.username} `
}

// 取消回复
const cancelReply = () => {
  replyTo.value = null
  commentContent.value = ''
}

// 获取父评论用户名
const getParentUsername = (comment) => {
  return comment.username
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    0: 'info',    // 未开始
    1: 'success', // 报名中
    2: 'warning', // 进行中
    3: 'info',    // 已结束
    4: 'danger'   // 已取消
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '未开始',
    1: '报名中',
    2: '进行中',
    3: '已结束',
    4: '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 判断是否可以报名
const canRegister = (activity) => {
  if (!userStore.isLoggedIn) return false

  const now = new Date()
  const registerStart = new Date(activity.registerStartTime)
  const registerEnd = new Date(activity.registerEndTime)
  return now >= registerStart && now <= registerEnd &&
      activity.status === 1 &&
      activity.registeredNumber < activity.recruitNumber &&
      !activity.isRegistered
}

// 获取报名按钮文本
const getRegisterButtonText = (activity) => {
  if (!userStore.isLoggedIn) return '请先登录'
  if (activity.isRegistered) return '已报名'
  if (activity.status === 0) return '未开始'
  if (activity.status === 2) return '进行中'
  if (activity.status === 3) return '已结束'
  if (activity.status === 4) return '已取消'
  if (activity.registeredNumber <= activity.recruitNumber) return '已满员'
  return '立即报名'
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  fetchActivityDetail()
  getCommentList()
})
</script>

<style scoped>
.activity-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.activity-header {
  display: flex;
  gap: 30px;
  margin-bottom: 30px;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.activity-cover {
  flex: 0 0 400px;
  height: 300px;
  border-radius: 8px;
  overflow: hidden;
}

.activity-cover .el-image {
  width: 100%;
  height: 100%;
}

.activity-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.activity-title {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 0;
}

.activity-meta {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
}

.activity-status {
  display: flex;
  align-items: center;
  gap: 20px;
}

.recruit-info {
  color: #606266;
}

.activity-actions {
  display: flex;
  gap: 15px;
  margin-top: auto;
}

.activity-content {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.detail-section {
  margin-bottom: 30px;
}

.detail-section h2 {
  font-size: 18px;
  color: #303133;
  margin-bottom: 15px;
}

.detail-section p {
  color: #606266;
  line-height: 1.6;
  margin: 10px 0;
}

.comment-input {
  margin-bottom: 30px;
}

.comment-input .comment-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}

.comment-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.comment-item {
  padding: 15px;
  border-radius: 8px;
  background: #f5f7fa;
  margin-bottom: 15px;
}

.sub-comments {
  margin-top: 15px;
  margin-left: 30px;
  border-left: 2px solid #e4e7ed;
  padding-left: 15px;
}

.sub-comments .comment-item {
  background: #fff;
  margin-bottom: 10px;
}

.sub-comments .sub-comments {
  margin-left: 20px;
}

.reply-to {
  color: #409EFF;
  margin-right: 5px;
}

.comment-user {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.username {
  font-weight: bold;
  color: #303133;
}

.time {
  color: #909399;
  font-size: 12px;
}

.comment-content {
  color: #606266;
  line-height: 1.6;
  margin: 10px 0;
}

.comment-actions {
  display: flex;
  gap: 20px;
}

.action {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #909399;
  cursor: pointer;
  transition: color 0.3s;
}

.action:hover {
  color: #409EFF;
}

@media (max-width: 768px) {
  .activity-header {
    flex-direction: column;
  }

  .activity-cover {
    flex: none;
    height: 200px;
  }
}
</style>
